package com.xwtech.cring.admin.pub;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;

import com.xwtech.framework.pub.po.FrameRole;
import com.xwtech.framework.pub.po.FrameLogin;
import com.xwtech.framework.login.pub.AbstractLoginToken;
import com.xwtech.cring.pub.dao.SysUserInfoDAO;
import com.xwtech.cring.admin.pub.AdminBaseInfo;
import com.xwtech.cring.admin.pub.MenuEntity;
import com.xwtech.cring.pub.po.SysUserInfo;
import com.xwtech.cring.pub.po.SysRoleRight;
import com.xwtech.cring.pub.dao.SysRoleDAO;
import com.xwtech.cring.pub.dao.SysRoleRightDAO;
import com.xwtech.framework.pub.dao.BaseJdbcDAO;
import com.xwtech.framework.pub.dao.FrameRoleDAO;
import com.xwtech.framework.pub.web.FrameworkApplication;

/**
 * 
 * <p>
 * Title: Framework
 * </p>
 * <p>
 * Description:Framework
 * </p>
 * <p>
 * Copyright: Copyright (c) 2005
 * </p>
 * <p>
 * Company: xwtech.com
 * </p>
 * 
 * @author starxu
 * @version 1.0
 * 
 * 登录令牌例子
 */
public class AdminLoginToken extends AbstractLoginToken {

	private SysUserInfoDAO sysUserInfoDAO = FrameworkApplication.cringDbCollection
			.getSysUserInfoDAO();

	private SysRoleDAO sysRoleDAO = FrameworkApplication.cringDbCollection
			.getSysRoleDAO();

	private SysRoleRightDAO sysRoleRightDAO = FrameworkApplication.cringDbCollection
			.getSysRoleRightDAO();

	private FrameRoleDAO frameRoleDAO = FrameworkApplication.cringDbCollection
			.getFrameRoleDAO();

	private BaseJdbcDAO baseJdbcDAO = FrameworkApplication.baseJdbcDAO;

	public void load(FrameLogin frameLogin) {
		// 设置登录信息
		this.setFrameLogin(frameLogin);

		AdminBaseInfo adminBaseInfo = new AdminBaseInfo();
		SysUserInfo sysUserInfo = sysUserInfoDAO
				.querySysUserInfoByLoginId(frameLogin.getLoginId());

		// 用户基本信息
		adminBaseInfo.setSysUserInfo(sysUserInfo);
		// 用户角色信息
		adminBaseInfo.setSysRole(sysRoleDAO
				.querySysRolesByUserInfoId(sysUserInfo.getUserInfoId()));

		// 设置用户扩展信息
		setBaseInfo(adminBaseInfo);

		// 设置用户权限
		List sysRoleRightList = sysRoleRightDAO
				.querySysRoleRightsBySysUserInfoId(sysUserInfo.getUserInfoId());
		if (sysRoleRightList != null) {
			String roleStr = "";
			FrameRole[] frameRoles = new FrameRole[sysRoleRightList.size()];
			Iterator it = sysRoleRightList.iterator();
			int k = 0;
			while (it.hasNext()) {
				SysRoleRight sysRoleRight = (SysRoleRight) it.next();
				roleStr += sysRoleRight.getRoleId() + ",";
				frameRoles[k] = frameRoleDAO.getFrameRole(sysRoleRight
						.getRoleId());
				k++;
			}
			setFrameRoles(frameRoles);

			// 用户登录时，根据用户的login_id得到他所拥有权限的所有Url的Set（此处单指后台管理的url权限），
			// 并存入token，放到session中，供过滤器AdminUserUrlFilter使用
			String filterUrlSql = "select t1.url_value from frame_url t1, frame_role t2,sys_role_right t3, sys_role t4, sys_user_role t5, "
					+ "sys_user_info t6 where t1.role_id = t2.role_id and t2.role_id = t3.role_id and t3.user_role_id = t4.role_id "
					+ "and t4.role_id = t5.role_id and t5.user_info_id = t6.user_info_id and t6.login_id = ? and t1.url_state = 'A' "
					+ "and t2.role_state = 'A' and t4.role_status = 'A' and t6.status = 'A'";
			List filterUrlList = baseJdbcDAO.getJdbcTemplate().queryForList(
					filterUrlSql, new Object[] { frameLogin.getLoginId() });
			Set urlSet = new HashSet();
			Iterator urlIterator = filterUrlList.iterator();
			while (urlIterator.hasNext()) {
				Map urlMap = (Map) urlIterator.next();
				if (urlMap.get("url_value") != null) {
					String url = urlMap.get("url_value").toString().trim();
					if (!url.equals("")) {
						// 如果该url带参数，则把后面的参数去掉
						if (url.indexOf("?") > 0) {
							url = url.substring(0, url.lastIndexOf("?"));
						}
						urlSet.add(url);
					}
				}
			}
			this.setUrlSet(urlSet);

			// 获取展现菜单所需数据
			List menuList = new ArrayList();
			String menuSql = "select t.submenu_id  from  frame_submenu t where t.menu_id = '0'";
			String subMenuSql = null;
			// 当用户是超级管理员(admin)时，直接提取所有能使用的menu给其使用
			if (frameLogin.getLoginName().equalsIgnoreCase(AdminUserBizConst.SUPER_ADMIN_LOGIN_NAME)) {
				subMenuSql = "select t1.submenu_id, t1.submenu_name, t1.menu_id, t2.url_value from frame_submenu t1, frame_url t2 where"
						+ " t1.url_id = t2.url_id and t1.submenu_state = 'A' and t2.url_state = 'A' order by t1.submenu_sort";
			} else {
				subMenuSql = "select t7.submenu_id, t7.submenu_name, t7.menu_id, t1.url_value from frame_url t1, frame_role t2, sys_role_right t3,"
						+ " sys_role t4, sys_user_role t5, sys_user_info t6, frame_submenu t7,frame_role_submenu t8 where t1.url_id = t7.url_id and "
						+ "t8.submenu_id = t7.submenu_id and t8.role_id = t2.role_id and t2.role_id = t3.role_id and t3.user_role_id = t4.role_id and "
						+ "t4.role_id = t5.role_id and t5.user_info_id = t6.user_info_id and t6.login_id = ? and t1.url_state = 'A' and t2.role_state = 'A' "
						+ "and t4.role_status = 'A' and t6.status = 'A' and t7.submenu_state = 'A' order by t7.submenu_sort";
			}
			// 获得根节点对应的id
			Long rootMenuId = Long.valueOf("0");
			List list = baseJdbcDAO.queryForList(menuSql);
			if (list != null && list.size() > 0) {
				Map map = (Map) list.get(0);
				rootMenuId = Long.valueOf(map.get("submenu_id").toString());
			}

			List subMenuList = null;
			if (frameLogin.getLoginName().equalsIgnoreCase("admin")) {
				subMenuList = baseJdbcDAO.queryForList(subMenuSql);
			} else {
				subMenuList = baseJdbcDAO.getJdbcTemplate().queryForList(
						subMenuSql, new Object[] { frameLogin.getLoginId() });
			}
			Iterator subMenuIterator = subMenuList.iterator();
			while (subMenuIterator.hasNext()) {
				Map subMenuMap = (Map) subMenuIterator.next();
				MenuEntity subEntity = new MenuEntity();
				// 获得父节点的id
				String menuId = subMenuMap.get("menu_id").toString();
				subEntity.setMenu_id(Long.valueOf(subMenuMap.get("submenu_id")
						.toString()));
				subEntity.setMenu_name(subMenuMap.get("submenu_name")
						.toString());
				// 如果父节点为根节点，则特殊处理
				if (menuId.equals(rootMenuId.toString())) {
					subEntity.setPid(Long.valueOf("0"));
				} else {
					subEntity.setPid(Long.valueOf(menuId));
					subEntity.setMenu_url(subMenuMap.get("url_value")
							.toString());
				}
				menuList.add(subEntity);
			}
			this.setMenuHtmlet(menuList);
		}
	}

	private void setMenuHtmlet(List list) {

		StringBuffer menuString = new StringBuffer();
		if (list != null && list.size() > 0) {
			menuString.append("<script>");
			menuString.append("var myMenu = new myMenu(0);");
			MenuEntity me = null;
			for (int i = 0; i < list.size(); i++) {
				me = (MenuEntity) list.get(i);
				menuString.append("myMenu.addNodes(" + me.getMenu_id() + ", "
						+ me.getPid() + ", '" + me.getMenu_name() + "', '', '"
						+ me.getMenu_url() + "', '_self');");
			}
			menuString.append("myMenu.createMenu();");
			menuString.append("</script>");
		}
		this.setMenuHtmlet(menuString.toString());
	}

}
